package com.example.testproject.adapter

import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.example.testproject.R
import com.example.testproject.bean.RvAdvancedBean
import kotlinx.android.synthetic.main.item_child_rv_advanced.view.*

/**
 *
 * @ClassName: RvAdvancedChildAdapter
 * @Author: android 超级兵
 * @CreateDate: 10/22/21$ 10:18 AM$
 * TODO
 */
class RvAdvancedChildAdapter(data: List<RvAdvancedBean.ChildBean>) :
    BaseQuickAdapter<RvAdvancedBean.ChildBean, BaseViewHolder>(R.layout.item_child_rv_advanced,
        data) {
    override fun convert(helper: BaseViewHolder, item: RvAdvancedBean.ChildBean) {

        helper.itemView.childCheckBox.isChecked = item.isChildSelect
        helper.itemView.childCheckBox.text = item.title

        helper
            .setText(R.id.tvPrice, String.format("单价:%d元", item.price))
            .setText(R.id.tvNumber, if (item.isChildSelect) {
                "${item.number}"
            } else "0")

        // 减商品
        helper.itemView.tvRemove.setOnClickListener {
            var tempNumber = item.number
            tempNumber--
            if (tempNumber <= 0) {
                tempNumber = 0
                item.isChildSelect = false
            }

            item.number = tempNumber
            notifyDataSetChanged()

            // 回调
            callBack()
        }

        // 添加商品
        helper.itemView.tvAdd.setOnClickListener {
            var tempNumber = item.number
            item.isChildSelect = true

            tempNumber++
            item.number = tempNumber
            notifyDataSetChanged()

            // 回调
            callBack()
        }


        // 点击
        helper.itemView.childCheckBox.setOnClickListener {
            var tempNumber = item.number

            // 是否选中
            val isChecked = helper.itemView.childCheckBox.isChecked

            // 选中状态
            if (isChecked) {
                //并且商品 > 0
                if (tempNumber >= 0) {
                    tempNumber = 1
                }
            } else {
                if (tempNumber >= 0) {
                    // 未选中 number = 0
                    tempNumber = 0
                }

            }
            item.isChildSelect = isChecked
            item.number = tempNumber
            notifyDataSetChanged()

            // 回调
            callBack()
        }
    }

    /*
     * 作者:android 超级兵
     * 创建时间: 10/22/21 11:22 AM
     * TODO 回调
     */
    private fun callBack() {
        var temp = 0
        repeat(data.size) {
            if (data[it].isChildSelect) {
                temp++
            }
        }

        childCallBack.childCallBack(temp)
    }

    interface RvChildCallBack {
        // 子条目回调
        fun childCallBack(temp: Int)
    }

    lateinit var childCallBack: RvChildCallBack

}